/* indent size: 2 */
const { Op } = require('sequelize');

module.exports = app => {
// 引入Sequelize
  const DataTypes = app.Sequelize;

  const Product = app.model.define('product', {
    id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      primaryKey: true,
      autoIncrement: true,
    },
    pcId: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'productclass',
        key: 'id'
      }
    },
    title: {
      type: DataTypes.STRING(255),
      allowNull: true
    },
    details: {
      type: DataTypes.STRING(255),
      allowNull: true
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false
    }
  }, {
    tableName: 'product'
  });

  Product.associate = function () {
    Product.belongsTo(app.model.ProductClass, { foreignKey: "pcId", targetKey: 'id' });
  }

  // 自定义查询方法，获取资源列表和总数
  Product.getResourcesAndCount = async (productId, options) => {
    const { offset, limit, where = {} } = options;

    const result = await app.model.transaction(async (t) => {
      // 使用事务以确保数据的一致性

      // 获取资源总数
      const count = await app.model.Resource.count({
        include: [
          {
            model: Product,
            where: { id: productId },
          },
        ],
        transaction: t,
      });

      // 获取资源列表
      const resources = await app.model.Resource.findAll({
        where: where,
        include: [
          {
            model: Product,
            where: { id: productId },
          },
        ],
        offset,
        limit,
        transaction: t,
      });

      return { count, resources };
    });

    return result;
  };

  return Product;
};
